package com.wht.bill.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bigkoo.pickerview.TimePickerView;
import com.wht.bill.R;
import com.wht.bill.activity.TallyBookNoteActivity;
import com.wht.bill.adapter.TallyDetailAdapter;
import com.wht.bill.bean.BillBean;
import com.wht.bill.bean.BillDetailBean;
import com.wht.bill.stickyheader.StickyHeaderGridLayoutManager;
import com.wht.bill.utils.CacheUtils;
import com.wht.bill.utils.DateUtils;
import com.wht.bill.utils.NumberUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 记账本--明细
 */
public class MenuFirstFragment extends BaseFragment {


    @BindView(R.id.data_year)
    TextView dataYear;
    @BindView(R.id.data_month)
    TextView dataMonth;
    @BindView(R.id.cash_surplus)
    TextView cashSurplus;
    @BindView(R.id.cash_compared)
    TextView cashCompared;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;
    @BindView(R.id.float_btn)
    FloatingActionButton floatBtn;


    private static final int SPAN_SIZE = 1;
    private StickyHeaderGridLayoutManager mLayoutManager;
    private TallyDetailAdapter adapter;
    private List<BillDetailBean.DaylistBean> list = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_menu_first;
    }


    @Override
    protected void initEventAndData() {

        dataYear.setText(DateUtils.getCurYear("yyyy"));
        dataMonth.setText(DateUtils.date2Str(new Date(), "MM"));
        //改变加载显示的颜色
        swipe.setColorSchemeColors(getResources().getColor(R.color.text_red), getResources().getColor(R.color.text_red));
        //设置向下拉多少出现刷新
        swipe.setDistanceToTriggerSync(200);
        //设置刷新出现的位置
        swipe.setProgressViewEndTarget(false, 200);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe.setRefreshing(false);
                setTestData();//恢复了假数据
            }
        });

        mLayoutManager = new StickyHeaderGridLayoutManager(SPAN_SIZE);
        mLayoutManager.setHeaderBottomOverlapMargin(5);

        // Workaround RecyclerView limitation when playing remove animations. RecyclerView always
        // puts the removed item on the top of other views and it will be drawn above sticky header.
        // The only way to fix this, abandon remove animations :(
        rvList.setItemAnimator(new DefaultItemAnimator() {
            @Override
            public boolean animateRemove(RecyclerView.ViewHolder holder) {
                dispatchRemoveFinished(holder);
                return false;
            }
        });
        rvList.setLayoutManager(mLayoutManager);
        adapter = new TallyDetailAdapter(mContext, list, new TallyDetailAdapter.onRefreshListener() {
            @Override
            public void onRefresh() {
                setTestData();
            }
        });
        rvList.setAdapter(adapter);
        //test data---------------
        setTestData();
    }


    private void setTestData() {
        try {
            list.clear();
            //获取账单
            List<BillBean> billList = CacheUtils.getBillList();
            //组装数据
            BillDetailBean billDetailBean = new BillDetailBean();
            billDetailBean.t_income = "0.00";
            billDetailBean.t_outcome = "0.00";
            List<BillBean> currentMonthList = new ArrayList<>();
            if (billList != null && !billList.isEmpty()) {
                for (BillBean billBean : billList) {
                    //筛选出当月的数据
                    if (TextUtils.equals(dataYear.getText().toString(), billBean.time.split("-")[0])
                            && TextUtils.equals(dataMonth.getText().toString(), billBean.time.split("-")[1])) {
                        currentMonthList.add(billBean);

                    }
                }
            }
            //循环当月的数据,用来组装数据
            double monthIncome = 0;
            double monthOutcome = 0;
            List<BillDetailBean.DaylistBean> daylist = new ArrayList<>();
            if (!currentMonthList.isEmpty()) {
                for (BillBean currentBillBean : currentMonthList) {
                    if (TextUtils.equals("1", currentBillBean.billType)) {
                        //支出
                        monthOutcome += NumberUtils.string2Double(currentBillBean.money);
                    } else {
                        //收入
                        monthIncome += NumberUtils.string2Double(currentBillBean.money);
                    }
                    //先判断是否有某一天的数据
                    boolean isContainsTarget = false;
                    for (BillDetailBean.DaylistBean dayListBean : daylist) {
                        if (TextUtils.equals(currentBillBean.time.split("-")[2], dayListBean.time)) {
                            isContainsTarget = true;
                            double income = 0;
                            double outcome = 0;
                            if (TextUtils.equals("1", currentBillBean.billType)) {
                                //每天的支出
                                outcome = NumberUtils.string2Double(dayListBean.outmoney)+NumberUtils.string2Double(currentBillBean.money);
                            } else {
                                //每天收入
                                income = NumberUtils.string2Double(dayListBean.inmoney)+NumberUtils.string2Double(currentBillBean.money);
                            }
                            //重新给每天的支出/收入赋值
                            dayListBean.outmoney = String.format("%.2f", outcome);
                            dayListBean.inmoney = String.format("%.2f", income);
                            //有,直接添加
                            dayListBean.list.add(currentBillBean);
                            break;
                        }
                    }
                    //如果没有
                    if (!isContainsTarget) {
                        BillDetailBean.DaylistBean daylistBean = new BillDetailBean.DaylistBean();
                        daylistBean.time = currentBillBean.time.split("-")[2];
                        if (TextUtils.equals("1", currentBillBean.billType)) {
                            //支出
                            daylistBean.outmoney = TextUtils.isEmpty(currentBillBean.money) ? "0.00" : currentBillBean.money;
                        } else {
                            //收入
                            daylistBean.inmoney = TextUtils.isEmpty(currentBillBean.money) ? "0.00" : currentBillBean.money;
                        }
                        daylistBean.list.add(currentBillBean);
                        daylist.add(daylistBean);
                    }
                }
                billDetailBean.t_income = String.format("%.2f", monthIncome);
                billDetailBean.t_outcome = String.format("%.2f", monthOutcome);
                billDetailBean.daylist.addAll(daylist);
            }
            //当月总支出
            cashSurplus.setText(billDetailBean.t_outcome);
            //当月总收入
            cashCompared.setText(billDetailBean.t_income);
            list = billDetailBean.daylist;
            adapter.setmDatas(list);
            adapter.notifyAllSectionsDataSetChanged();//需调用此方法刷新
        } catch (Exception e) {

        }
    }


    @OnClick({R.id.float_btn, R.id.layout_data})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.float_btn:
                Intent intent = new Intent(getContext(), TallyBookNoteActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_data:
                //时间选择器
                new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        dataYear.setText(DateUtils.date2Str(date, "yyyy"));
                        dataMonth.setText(DateUtils.date2Str(date, "MM"));
                        setTestData();
                    }
                })
                        .setRangDate(null, Calendar.getInstance())
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .build()
                        .show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setTestData();
    }
}
